# -*- coding: utf-8 -*-
"""
云存储适配器工厂
用于创建和管理不同的云存储适配器实例
"""

from typing import Dict, Type, Optional
from flask import current_app

from .base import CloudStorageAdapter
from .tianyi import TianyiCloudAdapter
from .local import LocalStorageAdapter


class CloudStorageFactory:
    """云存储适配器工厂类"""
    
    # 注册的适配器类
    _adapters: Dict[str, Type[CloudStorageAdapter]] = {
        'tianyi': TianyiCloudAdapter,
        'local': LocalStorageAdapter,
    }
    
    # 适配器实例缓存
    _instances: Dict[str, CloudStorageAdapter] = {}
    
    @classmethod
    def register_adapter(cls, provider: str, adapter_class: Type[CloudStorageAdapter]):
        """注册新的云存储适配器
        
        Args:
            provider: 提供商名称
            adapter_class: 适配器类
        """
        cls._adapters[provider] = adapter_class
    
    @classmethod
    def get_adapter(cls, provider: Optional[str] = None) -> CloudStorageAdapter:
        """获取云存储适配器实例
        
        Args:
            provider: 提供商名称，如果为None则使用默认配置
            
        Returns:
            CloudStorageAdapter: 适配器实例
            
        Raises:
            ValueError: 当提供商不支持时
            RuntimeError: 当配置缺失时
        """
        if provider is None:
            provider = current_app.config.get('CLOUD_STORAGE_PROVIDER', 'tianyi')
        
        # 检查是否已有实例
        if provider in cls._instances:
            return cls._instances[provider]
        
        # 检查是否支持该提供商
        if provider not in cls._adapters:
            raise ValueError(f"不支持的云存储提供商: {provider}")
        
        # 获取配置
        storage_config = current_app.config.get('CLOUD_STORAGE_CONFIG', {})
        provider_config = storage_config.get(provider, {})
        
        if not provider_config:
            raise RuntimeError(f"缺少 {provider} 云存储配置")
        
        # 创建适配器实例
        adapter_class = cls._adapters[provider]
        adapter = adapter_class(**provider_config)
        
        # 缓存实例
        cls._instances[provider] = adapter
        
        return adapter
    
    @classmethod
    def get_supported_providers(cls) -> list:
        """获取支持的云存储提供商列表
        
        Returns:
            list: 支持的提供商名称列表
        """
        return list(cls._adapters.keys())
    
    @classmethod
    def clear_cache(cls):
        """清空适配器实例缓存"""
        cls._instances.clear()
    
    @classmethod
    def test_all_connections(cls) -> Dict[str, bool]:
        """测试所有配置的云存储连接
        
        Returns:
            Dict[str, bool]: 各提供商的连接测试结果
        """
        results = {}
        storage_config = current_app.config.get('CLOUD_STORAGE_CONFIG', {})
        
        for provider in storage_config.keys():
            try:
                adapter = cls.get_adapter(provider)
                results[provider] = adapter.test_connection()
            except Exception as e:
                current_app.logger.error(f"测试 {provider} 连接失败: {str(e)}")
                results[provider] = False
        
        return results


# 便捷函数
def get_default_adapter() -> CloudStorageAdapter:
    """获取默认的云存储适配器
    
    Returns:
        CloudStorageAdapter: 默认适配器实例
    """
    return CloudStorageFactory.get_adapter()


def get_adapter_by_provider(provider: str) -> CloudStorageAdapter:
    """根据提供商获取适配器
    
    Args:
        provider: 提供商名称
        
    Returns:
        CloudStorageAdapter: 适配器实例
    """
    return CloudStorageFactory.get_adapter(provider)